package edu.spsu.cs4253;

import java.io.*;
import java.net.*;

public class TCPClientServer {
	public static void main (String[] args) {
		//Replace file
		final String file = "/Users/kdebrito/Desktop/3disp_eval11-1.exe";
		final int bufferSize = 65536;
		final String temp;
		final BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
		final String servPort = "8089";
		final String hostName = "localhost";

		new Thread(new Runnable() {
			public void run() {
				try {
					int serverPort = Integer.parseInt(servPort);
					System.out.println("Creating Server Socket.....");
					ServerSocket serverSocket = new ServerSocket(serverPort);
					System.out.println("Server Port: " + serverPort);
					Socket clientSocket = serverSocket.accept();
					System.out.println("Connected......");
					long startTime = System.currentTimeMillis();
					byte[] buffer = new byte[bufferSize];
					int read;
					int totalRead = 0;
					InputStream clientInputStream = clientSocket.getInputStream();
					while((read = clientInputStream.read(buffer)) != -1) {
						totalRead += read;
					}
					long endTime = System.currentTimeMillis();
					System.out.println(totalRead + " bytes read in " + (endTime - startTime) + " ms.");
				}
				catch(IOException e) {
					
				}
			}
		}).start();
		
		new Thread(new Runnable() {
			public void run() {
				try{
				Thread.sleep(1000);
				int serverPort = Integer.parseInt(servPort);
				System.out.println("Creating Socket.....");
				Socket socket = new Socket(hostName, serverPort);
				FileInputStream in = new FileInputStream(file);
				OutputStream out = socket.getOutputStream();
				long startTime = System.currentTimeMillis();
				byte[] buffer = new byte[bufferSize];
				int read;
				int readTotal = 0; 
				while((read = in.read(buffer)) != -1) {
					out.write(buffer, 0, read);
					readTotal += read;
				}
				out.close();
				in.close();
				socket.close();
				long endTime = System.currentTimeMillis();
				System.out.println(readTotal + " bytes written in " + (endTime - startTime) + " ms.");
			}
				
				catch(Exception e) {
					
				}
				
			}
		}).start();
	}
}
